//author:jxx
import store from "@/store/index";
//此处是对表单的方法，组件，权限操作按钮等进行任意扩展(方法扩展可参照SellOrder.js)
let extension = {
  components: {
    //动态扩充组件或组件路径
    //表单header、content、footer对应位置扩充的组件
    gridHeader: () => import("./distributor/distributor.vue"), //{ template: "<div>扩展组xx件</div>" },
    gridBody: "",
    gridFooter: "",
    //弹出框(修改、编辑、查看)header、content、footer对应位置扩充的组件
    modelHeader: "",
    modelBody: "",
    modelFooter: ""
  },
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //事件扩展
    getOption (field) {
      let option;
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    onInit () {
      //新建窗口的宽和高
      this.boxOptions.width = 1000;
      this.boxOptions.height = 600;
      //    单选、不显示复选框、显示序号
      this.textInline = true;
      let spare10 = this.getOption("spare10");
      let smsId = this.getOption("smsId");
      let distributorType = this.getOption("distributorType");
      this.http
        .post("/api/Dictionary/GetVueDictionary", ["distributor_Type"])
        .then(res => {
          if (res) {
            if (res.length > 0) {
              let arr = [];
              res[0].data.forEach(item => {
                if (item.value == "直营分销" || item.value == "直营" || item.value == "公众号") {
                  arr.push(item);
                }
              });
              distributorType.data = arr
            }
          }
        });
      let productType = this.getOption('productType')
      smsId.onChange = (val, option) => {
        spare10.hidden = false;
        let data = option.data.filter(item => item.key == val);
        if (data.length > 0) {
          this.editFormFields[spare10.field] = data[0].remark;
        } else {
          spare10.hidden = true;
        }
      };
      this.http.post("/api/Dictionary/GetVueDictionary", ['tree_protype'])
        .then(resd => {
          this.columns.forEach(i => {
            if (i.field == 'productType') {
              i.bind.data = resd[0].data.map(i => {
                return {
                  value: i.value,
                  key: i.id
                }
              })
            }
          })
        });
      this.http.get("api/producttypes/GetDistriProductType")
        .then(res => {
          productType.data = res.data
        });

      // 定义 watch 函数
      function watcsh (target, prop, callback) {
        const handler = {
          get (target, key, receiver) {
            return Reflect.get(target, key, receiver);
          },
          set (target, key, value, receiver) {
            const oldValue = target[key];
            const result = Reflect.set(target, key, value, receiver);

            if (key === prop && oldValue !== value) {
              callback(value, oldValue);
            }

            return result;
          },
          deleteProperty (target, key) {
            const oldValue = target[key];
            const result = Reflect.deleteProperty(target, key);

            if (key === prop) {
              callback(undefined, oldValue);
            }

            return result;
          }
        };

        return new Proxy(target, handler);
      }

      // 定义回调函数


      // 创建一个代理对象并绑定 watch
      // const proxyData = watch(data, 'age', watchCallback);

      productType.onChange = (val, option) => {
        let sc = JSON.parse(JSON.stringify(this.editFormFields.productType))
        // console.log("%c 🇲🇵: productType.onChange -> val ", "font-size:16px;background-color:#53a434;color:white;", sc, val)
        // this.editFormFields.productType.push(val)
      //   const watchCallback = (newValue, oldValue) => {
      //     console.log(`Property changed: ${oldValue} -> ${newValue}`);
      //   };
      // const asd= watcsh(this.editFormFields, 'productType', watchCallback);
      // console.log("%c 🦀: productType.onChange -> asd ", "font-size:16px;background-color:#7cdff3;color:black;", asd.productType)

      };
    },
    searchBefore (param) {
      let wheres = {
        name: "distributorType",
        value: "2006,2004",
        displayType: "checkbox"
      };
      param.wheres.push(wheres);
      return true;
    },
    rowClick ({ row, column, event }) {
      //查询界面table点击行选中当前行
      this.$refs.table.$refs.table.toggleRowSelection(row);
      return true;
    },
    direct () {
      let _userInfo = store.getters.getUserInfo();
      let distributorCode = this.getOption("distributorCode");
      let distributorName = this.getOption("distributorName");
      let productType = this.getOption("productType");
      let epidemicReminder = this.getOption("epidemicReminder");
      let pay_code = this.getOption("pay_code");
      let isMessage = this.getOption("isMessage");
      let isShow = this.getOption("isShow");
      let smsId = this.getOption("smsId");
      let smsMode = this.getOption("smsMode");
      let signCode = this.getOption("signCode"); //短信签名
      let contactPerson = this.getOption("contactPerson");
      let contactPhone = this.getOption("contactPhone");
      let scancodeUrl = this.getOption("scancodeUrl");
      let spare15 = this.getOption("spare15");
      let shareImg = this.getOption("shareImg");
      let diyImg = this.getOption("diyImg");
      let timeContainer = this.getOption("timeContainer"); //起止时间
      let appId = this.getOption("appId"); //起止时间
      let appSecret = this.getOption("appSecret"); //起止时间
      // let distributorEndTime = this.getOption("distributorEndTime");
      // let distributorStartTime = this.getOption("distributorStartTime");
      distributorCode.hidden = false;
      distributorCode.required = true;
      productType.hidden = false;
      epidemicReminder.hidden = false;
      distributorName.hidden = false;
      distributorName.required = true;
      appId.hidden = false;
      appId.required = true;
      appSecret.hidden = false;
      appSecret.required = true;
      pay_code.hidden = false;
      pay_code.required = true;
      isMessage.hidden = false;
      isShow.hidden = false;
      if (this.editFormFields[isMessage.field] == 1) {
        smsId.required = true;
        smsMode.required = true;
        signCode.required = true;
      }
      smsId.hidden = false;
      smsMode.hidden = false;
      signCode.hidden = false;
      contactPerson.hidden = false;
      //contactPerson.required=true;
      contactPhone.hidden = false;
      spare15.hidden = false;
      shareImg.hidden = false;
      diyImg.hidden = false;
      scancodeUrl.hidden = false;
      timeContainer.hidden = false;
      timeContainer.required = true;
      // distributorEndTime.hidden = false;
      // distributorEndTime.required = true;
      // distributorStartTime.hidden = false;
      // distributorStartTime.required = true;
    },
    notdirect () {
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (
            item.field != "distributorType" &&
            item.field != "creator" &&
            item.field != "createDate" &&
            item.field != "modifier" &&
            item.field != "modifyDate"
          ) {
            item.hidden = true;
            item.required = false;
          }
        });
      });
    },
    async modelOpenBeforeAsync (row) {
      let smsId = this.getOption("smsId");
      let smsMode = this.getOption("smsMode");
      let signCode = this.getOption("signCode");
      let spare10 = this.getOption("spare10");
      let distributorType = this.getOption("distributorType");
      let isMessage = this.getOption("isMessage");

      if (row.distributorType == 2004 || row.distributorType == 2006) {
        this.direct();
      } else {
        this.notdirect();
      }
      distributorType.onChange = (val, option) => {
        if (val == 2004 || val == 2006) {
          this.direct();
        } else {
          this.notdirect();
        }
      };
      if (this.editFormFields[isMessage.field] == 1 || row.isMessage == 1) {
        smsId.hidden = false;
        smsMode.hidden = false;
        signCode.hidden = false;
        smsId.required = true;
        smsMode.required = true;
        signCode.required = true;
      } else {
        this.editFormFields[signCode.field] = "";
        this.editFormFields[smsId.field] = "";
        this.editFormFields[smsMode.field] = "";
        smsId.hidden = true;
        smsMode.hidden = true;
        signCode.hidden = true;
        spare10.hidden = true;
        smsId.required = false;
        smsMode.required = false;
        signCode.required = false;
      }
      isMessage.onChange = (val, option) => {
        if (val == 1) {
          smsId.hidden = false;
          smsMode.hidden = false;
          signCode.hidden = false;
          smsId.required = true;
          smsMode.required = true;
          signCode.required = true;
        } else {
          this.editFormFields[signCode.field] = "";
          this.editFormFields[smsId.field] = "";
          this.editFormFields[smsMode.field] = "";
          smsId.hidden = true;
          smsMode.hidden = true;
          signCode.hidden = true;
          spare10.hidden = true;
          smsId.required = false;
          smsMode.required = false;
          signCode.required = false;
        }
      };
      if (this.currentAction == "Add") {

      } else {
        if (row.productType) {
          let arr = row.productType.split(',')
          this.editFormFields.productType = []
          arr.forEach(v => {
            this.editFormFields.productType.push(Number(v))
          })
        }

      }
      return true;
    },
    // 点击编辑/新建按钮弹出框后
    async modelOpenAfter (row) {
      if (this.currentAction == "update") {
        this.editFormFields.timeContainer = [
          row.distributorStartTime,
          row.distributorEndTime
        ];
      } else {
        let distributorName = this.getOption("distributorName");
        let distributorCode = this.getOption("distributorCode");
        distributorName.onInput = val => {
          this.editFormFields[
            distributorCode.field
          ] = this.base.chineseToPinYin(val);
        };
        this.editFormFileds.isShow = 0
      }
    },
    addBefore (formData) {
      //新建保存前formData为对象，包括明细表
      return this.veriFromTable(formData);
    },
    updateBefore (formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return this.veriFromTable(formData);
    },
    // 保存前编辑
    veriFromTable (formData) {
      console.log("保存前编辑", formData);
      let timeContainer = formData.mainData.timeContainer.split(",");
      if (timeContainer.length > 0 && timeContainer[0] != "") {
        formData.mainData.distributorStartTime = timeContainer[0];
        formData.mainData.distributorEndTime = timeContainer[1];
      } else {
        this.$Message.error("请选择有效起止日期！");
      }
      return true;
    }
  }
};
export default extension;
